// navbar.js - 导航栏初始化与用户信息显示

function initNavbar() {
    // 等待AuthManager和PermissionManager都初始化
    const checkReady = () => {
        if (window.AuthManager && window.PermissionManager) {
            _doInitNavbar();
        } else {
            setTimeout(checkReady, 100);
        }
    };
    checkReady();
}

function _doInitNavbar() {
    // 获取用户信息
    const userInfo = window.AuthManager.getUserInfo();
    if (!userInfo) {
        const token = window.AuthManager.getToken();
        if (!token) {
            window.location.href = '/ercms/login';
            return;
        } else {
            window.AuthManager.userInfo = JSON.parse(localStorage.getItem('user_info') || 'null');
            if (!window.AuthManager.userInfo) {
                window.location.href = '/ercms/login';
                return;
            }
        }
    }
    // 初始化权限管理器
    if (window.PermissionManager) {
        window.PermissionManager.init(userInfo);
    }
    // 显示用户信息
    const userInfoDiv = document.getElementById('user-info');
    const userNameSpan = document.getElementById('user-name');
    const userRoleBadge = document.getElementById('user-role-badge');
    if (userInfoDiv && userNameSpan) {
        userInfoDiv.style.display = 'flex';
        userNameSpan.textContent = userInfo.realName || userInfo.username;
        // 设置角色badge
        if (userRoleBadge && userInfo.role) {
            let roleText = '';
            let badgeClass = 'user-role-badge badge fw-bold';
            switch (userInfo.role) {
                case 'ADMIN': roleText = '系统管理员'; badgeClass += ' bg-primary'; break;
                case 'DEPT_MANAGER': roleText = '部门管理员'; badgeClass += ' bg-success'; break;
                case 'DISPATCHER': roleText = '调度员'; badgeClass += ' bg-warning text-dark'; break;
                case 'END_USER': roleText = '终端用户'; badgeClass += ' bg-secondary'; break;
                default: roleText = userInfo.role; badgeClass += ' bg-secondary';
            }
            userRoleBadge.textContent = roleText;
            userRoleBadge.className = badgeClass;
        }
    }
    // 根据权限控制导航项显示
    setupNavigationPermissions();
    // 设置当前页面高亮
    const currentPage = window.location.pathname.split('/').pop() || 'dashboard';
    const navLinks = document.querySelectorAll('.nav-link[data-page]');
    navLinks.forEach(link => {
        if (link.getAttribute('data-page') === currentPage) {
            link.classList.add('active');
        }
    });
    // 绑定退出登录事件
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', async function() {
            if (confirm('确定要退出登录吗？')) {
                try {
                    logoutBtn.disabled = true;
                    logoutBtn.innerHTML = '<i class="bi bi-hourglass-split"></i>';
                    await window.AuthManager.logout();
                } catch (error) {
                    logoutBtn.disabled = false;
                    logoutBtn.innerHTML = '<i class="bi bi-box-arrow-right"></i>';
                    alert('退出登录失败，请重试');
                }
            }
        });
    }
}

function setupNavigationPermissions() {
    if (!window.PermissionManager) {
        return;
    }
    // 调度中心 - 只有调度员和系统管理员可以访问
    const dispatchNav = document.getElementById('dispatch-nav');
    if (dispatchNav) {
        if (window.PermissionManager.hasPermission('DISPATCH_CENTER', 'access')) {
            dispatchNav.style.display = 'block';
        }
    }
    // 资源调度 - 只有系统管理员、部门经理和调度员可以访问
    const resourceNav = document.getElementById('resource-nav');
    if (resourceNav) {
        if (window.PermissionManager.hasPermission('RESOURCE_MANAGEMENT', 'access')) {
            resourceNav.style.display = 'block';
        }
    }
    // 部门管理 - 只有系统管理员和部门经理可以访问
    const departmentNav = document.getElementById('department-nav');
    if (departmentNav) {
        if (window.PermissionManager.hasPermission('DEPARTMENT_MANAGEMENT', 'access')) {
            departmentNav.style.display = 'block';
        }
    }
    // 用户管理 - 只有系统管理员和部门经理可以访问
    const userNav = document.getElementById('user-nav');
    if (userNav) {
        if (window.PermissionManager.hasPermission('USER_MANAGEMENT', 'access')) {
            userNav.style.display = 'block';
        }
    }
    // 报告管理 - 只有系统管理员、部门经理和调度员可以访问
    const reportNav = document.getElementById('report-nav');
    if (reportNav) {
        if (window.PermissionManager.hasPermission('REPORT_MANAGEMENT', 'access')) {
            reportNav.style.display = 'block';
        }
    }
}

// 页面加载后自动初始化导航栏
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initNavbar);
} else {
    initNavbar();
}

// 导出全局
window.initNavbar = initNavbar; 